//
//  GroupViewController.m
//  EMMApp
//
//  Created by Mac on 16/5/17.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "GroupViewController.h"
#import "HuxingCell.h"
#import "GetPremisesListApi.h"

@interface GroupViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) NSMutableArray *seleArr;

@property (nonatomic, strong) NSMutableArray *arr;

@property (nonatomic, strong) NSMutableArray *arrId;

@property (nonatomic, strong) UILabel *jlLabel; //当前没有记录

@end

@implementation GroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _seleArr = [[NSMutableArray alloc] init];
    _arr = [[NSMutableArray alloc] init];
    _arrId = [[NSMutableArray alloc] init];
    
    [self creatNavigationController];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _jlLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, EMM_WIDTH, 20)];
    _jlLabel.textAlignment = NSTextAlignmentCenter;
    _jlLabel.text = @"当前没有记录";
    _jlLabel.font = [UIFont systemFontOfSize:16];
    _jlLabel.hidden = YES;
    [self.view addSubview:_jlLabel];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _dataArr = [[NSMutableArray alloc] init];
    [self postGetCustomerDetailApi];
}

#pragma mark - api
- (void)postGetCustomerDetailApi {
    
    GetPremisesListApi *api = [[GetPremisesListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetPremisesListApi *result = (GetPremisesListApi *)request;
        if (result.isSuccess) {
            GetPremisesList *get = result.resultData;
            for (PremisesList *list in get.premisesList) {
                [_dataArr addObject:list];
            }
            if (_dataArr.count > 0) {
                _tableView.hidden = NO;
                _jlLabel.hidden = YES;
            } else {
                _tableView.hidden = YES;
                _jlLabel.hidden = NO;
            }
            
            for (int i = 0; i < _dataArr.count; i++) {
                PremisesList *premisesList  = [_dataArr objectAtIndex:i];;
                for (int j = 0; j < _recordArr.count; j++) {
                    NSString *name2 = [_recordArr objectAtIndex:j];
                    if ([premisesList.premisesName isEqualToString:name2]) {
                        [_seleArr addObject:[NSString stringWithFormat:@"%d", i]];
                    }
                }
            }
            
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                [appInstance showLogin];
                
            } else if ( [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_tableView reloadData];
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 导航

- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"意向组团";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick:)];
    [leftItem setTintColor:[UIColor colorFromHexCode:@"#ff7200"]];
    [self.navigationItem setLeftBarButtonItem:leftItem];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick:)];
    [rightItem setTintColor:[UIColor colorFromHexCode:@"#ff7200"]];
    [self.navigationItem setRightBarButtonItem:rightItem];
    
}

- (void)leftItemClick:(UIButton *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightItemClick:(UIButton *)btn {
    if (_seleArr.count == 0) {
        [self showToast:@"请选意向组团"];
        return;
    }
    
    for (int i = 0; i < _seleArr.count; i++) {
        NSString *string = [_seleArr objectAtIndex:i];
        PremisesList *list = [_dataArr objectAtIndex:[string intValue]];
        [_arr addObject:list.premisesName];
        [_arrId addObject:@{@"premisesId":list.premisesId}];
    }
   
    if (_groupBlock) {
        _groupBlock(_arr,_arrId);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"HuxingCellId";
    HuxingCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"HuxingCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 49.5, EMM_WIDTH-20, 0.5)];
    lineImage.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    [cell addSubview:lineImage];
    PremisesList *list = [_dataArr objectAtIndex:indexPath.row];
    cell.huxingNameLabel.text = list.premisesName;
    NSString *string = [NSString stringWithFormat:@"%ld",indexPath.row];
    if ([_seleArr containsObject:string]) {
        cell.huxingImageView.image = [UIImage imageNamed:@"choose"];
    }else {
        cell.huxingImageView.image = [UIImage imageNamed:@"choose_no"];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *string = [NSString stringWithFormat:@"%ld",indexPath.row];
    if ([_seleArr containsObject:string]) {
        [_seleArr removeObject:string];
    } else {
        [_seleArr addObject:string];
    }
    [_tableView reloadData];
}



@end
